<?php


namespace app\admin\member\model;

use Exception;
use mb\helper\Collection;
use think\Db;

class Withdrawal
{
    protected static $table = 'member_withdrawals';
    /**
     * @param array $row
     * @return bool|int|string
     */
    public static function add(array $row)
    {
        $newRow = Collection::elements([
            'memberId',
            'target',
            'targetId',
            'money',
            'realMoney',
            'status',
            'msg',
            'afterMoney',
            'adminId',
            'timeClosed',
            'type',
            'ghost',
            'staffId',
            'teamId',
        ], $row);
        $newRow['timeCreated'] = time();
        $newRow['existence'] = 1;
        $newRow = Collection::keyStyle($newRow, Collection::NAME_STYLE_C);
        try {
            $count = Db::table(self::$table)->where(['member_id' => $newRow['member_id'],'status' => 'success'])->count();
            $count++;
            $newRow['number'] = $count;
            return Db::table(self::$table)
                ->insertGetId($newRow);
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
    }

    /**
     * @param $filter
     * @return array|Error
     */
    public static function fetch($filter)
    {
        $where = self::parseFilters($filter);
        try {
            $row = Db::table(self::$table)
                ->where($where)
                ->find();
            if (!empty($row)) {
                $row['time_created'] *= 1000;
                return Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }

    /**
     * @param $filter
     * @return bool|Error
     */
    public static function remove($filter)
    {
        $where = self::parseFilters($filter);
        try {
            $offect = Db::table(self::$table)
                ->where($where)
                ->delete();
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @param $newState
     * @return bool|Error
     */
    public static function update($filter, $newState)
    {
        $where = self::parseFilters($filter);
        try {
            $offect = Db::table(self::$table)
                ->where($where)
                ->update($newState);
            if ($offect === 1) {
                return true;
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return $offect;
    }

    /**
     * @param $filter
     * @return array
     */
    public static function parseFilters($filter)
    {
        $where = [];
        if (is_array($filter)) {
            if (!empty($filter['id'])) {
                $where[] = ['id', '=', $filter['id']];
            }
            if (!empty($filter['memberId'])) {
                $where[] = ['member_id', '=', $filter['memberId']];
            }
            if (empty($where)) {
                throw error(-10, '参数错误必须指定id');
            }
        } else {
            $where[] = ['id', '=', intval($filter)];
        }
        return $where;
    }

    /**
     * @param array $filters
     * @param int $pIndex
     * @param int $pSize
     * @param int $total
     * @return array|Error
     */
    public static function search(array $filters, int $pIndex = 0, int $pSize = 10, int &$total = 0)
    {
        $where = self::parseSearchFilters($filters);
        try {
            if (!empty($pIndex)) {
                $total = Db::table(self::$table)
                    ->where($where)
                    ->count();
            }
            $query = Db::table(self::$table)
                ->where($where);
            if (!empty($pIndex)) {
                $query->page($pIndex, $pSize);
            }
            if (!empty($filters['order'])) {
                $query->order($filters['order']);
            }
            $dataSet = $query->select();
            if (!$dataSet->isEmpty()) {
                return $dataSet->map(
                    function ($row) {
                        $row['time_created'] *= 1000;
                        $row = Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
                        return $row;
                    }
                )->toArray();
            }
        } catch (Exception $e) {
            return error($e->getCode(), $e->getMessage());
        }
        return [];
    }

    public static function sumFiled($filters,$filed)
    {
        $where = self::parseSearchFilters($filters);
        try {
            return Db::table(self::$table)->where($where)->sum($filed);
        }catch (Exception $e) {
            return 0;
        }
    }

    public static function parseSearchFilters($filters)
    {
        $where = [];
        if (!empty($filters['status'])) {
            $where[] = ['status', '=', $filters['status']];
        }
        if (!empty($filters['statuses'])) {
            $where[] = ['status', 'in', $filters['statuses']];
        }
        if (!empty($filters['memberId'])) {
            $where[] = ['member_id', '=', $filters['memberId']];
        }
        if (!empty($filters['memberIds'])) {
            $where[] = ['member_id','in',$filters['memberIds']];
        }
        if (!empty($filters['timeCreatedStart'])) {
            $where[] = ['time_created', '>=', $filters['timeCreatedStart']];
        }
        if (!empty($filters['timeCreatedEnd'])) {
            $where[] = ['time_created', '<=', $filters['timeCreatedEnd']];
        }
        if (isset($filters['ghost'])) {
            $where[] = ['ghost','=',$filters['ghost']];
        }
        if (!empty($filters['existence'])) {
            $where[] = ['existence', '=', $filters['existence']];
        }
        if (!empty($filters['staffId'])) {
            $where[] = ['staff_id', '=', $filters['staffId']];
        }
        if (!empty($filters['teamId'])) {
            $where[] = ['team_id', '=', $filters['teamId']];
        }
        if (!empty($filters['type'])) {
            $where[] = ['type', '=', $filters['type']];
        }
        return $where;
    }

    public static function water($memberId)
    {
        try {
            //获取订单总金额
            $water = Db::table('product_orders')
                ->where(['member_id' => $memberId])
                ->sum('money_order');
            //获取手动添加流水
            $userWater = Db::table('members')
                ->where(['id' => $memberId])
                ->value('water');
            //总流水
            $water += $userWater;

            //获取提现总数
            $withdrawalMoney = 0;
            $withdrawal = Withdrawal::search(['memberId' => $memberId]);
            foreach ($withdrawal as $w) {
                if ($w['status'] == 'created' || $w['status'] == 'success') {
                    $withdrawalMoney += $w['money'];
                }
            }

            return [
                'water' => $water,
                'userWater' => $userWater,
                'withdrawal' => $withdrawalMoney
            ];
        } catch (Exception $e) {

        }
        return [
            'water' => 0,
            'userWater' => 0,
            'withdrawal' => 0
        ];
    }
}